/**
 * @description:
 * @file: app.ts
 * @author: Evan
 * @date: 2025.04.08 10:49:27
 * @week: 周二
 * @version: V
 * */

import { defineStore } from 'pinia'
import { setStorage, getStorage } from '@/utils/storage'
import i18n from '@/locales'
import router from '@/router'
import { useDark } from '@vueuse/core'

// 环境变量
const env = import.meta.env

import type { AppStore, ModuleItem } from './type'
import type { Language } from '@/locales/type'

// 皮肤 key
const skinkey = 'app_skin'
// 菜单展开 key
const sidebarIsopenKey = 'app_sider_status'

const skin = getStorage(skinkey) || 'light'

if (skin == 'dark') {
  document.documentElement.classList.add('dark')
}

// 多语言
const locale = i18n.global.locale.value as import('@/locales/type').Language

// 是否正式环境
const isProd = env.VITE_MODE == 'production'

const appStore: AppStore = {
  title: 'Vue + Ts 前端训练场',

  i18n: true,
  language: locale,
  isEn: locale == 'en',

  isProd,
  hrefToken: false,

  // 大屏
  showDb: !true,
  // 消息中心
  showNotice: !true,
  // 警告信息
  showWarn: !true,

  // 切换项目
  changeProjectSwitch: false,

  // 首页是否自动有权限的界面跳转
  isAutoJump: false,
  // 菜单禁用功能开关
  menuDisabledSwitch: true,

  logo: {
    custom: true,
    normal: '/sys/logo-v.png',
    small: '/sys/logo.png'
  },

  // 皮肤
  skin,
  toggleSkin: true,

  tag: {
    // 是否展示
    show: true
  },

  sidebar: {
    hasToggleBtn: true,
    opened: getStorage(sidebarIsopenKey) == '1',
    withoutAnimation: false
  },

  navbar: {
    show: true,
    hasBreadcrumb: true
  },

  // 模块
  module: {
    show: !true,
    current: 'cm',
    active: 'cm',
    list: [],
    menuList: []
  },

  // 系统端口号
  systemPortMap: {
    sso: 9002
  }
}

export const useAppStore = defineStore('app', {
  state: () => appStore,

  getters: {},
  actions: {
    // 更新 logo 信息
    updateLogo(opts: { normal: string; small: string }) {
      if (opts.normal) {
        this.logo.normal = opts.normal
      }
      if (opts.small) {
        this.logo.small = opts.small
      }
      let status = Boolean(opts.normal || opts.small)
      this.logo.custom = status
    },

    // 更新主题
    updateSkin(skin: string) {
      document.documentElement.classList.remove(this.skin)
      this.skin = skin

      const isDark = useDark()
      isDark.value = skin == 'dark'
      setStorage(skinkey, skin)
      document.documentElement.classList.add(skin)
    },

    // 更新侧边栏展开/收起
    toggleSideBar() {
      const sidebar = this.sidebar
      sidebar.opened = !sidebar.opened
      sidebar.withoutAnimation = false
      if (sidebar.opened) {
        setStorage(sidebarIsopenKey, '1')
      } else {
        setStorage(sidebarIsopenKey, '0')
      }
    },

    // 更新语言
    updateLangeuage(language: Language) {
      i18n.global.locale.value = language
      setStorage('LANGUAGE', language)
      this.$patch({
        isEn: language == 'en',
        language
      })
    },

    // 模块列表
    updateModules(list: ModuleItem[], menuList: import('@/api/request/type').NavItem[] = []) {
      this.module.list = list
      this.module.menuList = menuList
    },

    // 检测权限
    checkAuth(code?: string) {
      const route = router.currentRoute.value
      const sn = route?.meta?.sn as string
      if (!sn) return true

      const menuList = this.module.menuList
      const findModule = (list: import('@/api/request/type').NavItem[] = []) => {
        let menu: import('@/api/request/type').NavItem | undefined
        list.some(item => {
          if (item.code == sn) {
            menu = item
            return true
          } else {
            menu = findModule(item.children || [])
            if (!!menu) return true
          }
          return false
        })
        return menu
      }
      const list = findModule(menuList)?.children || []
      return list.findIndex(item => item.code === code) > -1
    },

    // 模块状态
    updateModuleStatus(active: string) {
      this.module.active = active
    },

    // 跳转系统
    toSystem(sys: string, path = '') {
      // 获取当前地址
      let location = window.location
      let origin = location.origin,
        search = location.search

      let href = `${origin}/${sys || ''}${path}${search}`
      // 正式环境
      if (env.VITE_MODE === 'dev') {
        const { protocol, hostname } = location
        href = `${protocol}//${hostname}:${
          this.systemPortMap[sys as keyof AppStore['systemPortMap']] || this.systemPortMap.sso
        }/${sys}${path}`
      }
      window.location.href = href
    }
  }
})
